package com.itfreer.utils.common;

import android.content.Context;

import java.lang.reflect.Field;

/**
 * 获取资源工具类
 */
public class ResourceUtils {

    private static Class<?> CDrawable = null;
    private static Class<?> CLayout = null;
    private static Class<?> CId = null;
    private static Class<?> CAnim = null;
    private static Class<?> CStyle = null;
    private static Class<?> CString = null;
    private static Class<?> CArray = null;

    public static int getDrawableId(Context content, String resName){
        try{
            CDrawable = Class.forName(content.getPackageName() + ".R$drawable");
            return getResId(CDrawable, resName);
        }catch(ClassNotFoundException e){

        }
        return -1;
    }

    public static int getLayoutId(Context content, String resName){
        try{
            CLayout = Class.forName(content.getPackageName() + ".R$layout");
            return getResId(CLayout, resName);
        }catch(ClassNotFoundException e){

        }
        return -1;
    }

    public static int getIdId(Context content, String resName){
        try{
            CId = Class.forName(content.getPackageName() + ".R$id");
            return getResId(CId, resName);
        }catch(ClassNotFoundException e){

        }
        return -1;
    }

    public static int getAnimId(Context content, String resName){
        try{
            CAnim = Class.forName(content.getPackageName() + ".R$anim");
            return getResId(CAnim, resName);
        }catch(ClassNotFoundException e){

        }
        return -1;
    }

    public static int getStyleId(Context content, String resName){
        try{
            CStyle = Class.forName(content.getPackageName() + ".R$style");
            return getResId(CStyle, resName);
        }catch(ClassNotFoundException e){

        }
        return -1;
    }

    public static int getStringId(Context content, String resName){
        try{
            CString = Class.forName(content.getPackageName() + ".R$string");
            return getResId(CString, resName);
        }catch(ClassNotFoundException e){

        }
        return -1;
    }

    public static int getArrayId(Context content, String resName){
        try{
            CArray = Class.forName(content.getPackageName() + ".R$array");
            return getResId(CArray, resName);
        }catch(ClassNotFoundException e){

        }
        return -1;
    }

    private static int getResId(Class<?> resClass, String resName){
        if(resClass == null){

            throw new IllegalArgumentException("ResClass is not initialized. Please make sure you have added neccessary resources. Also make sure you have .R$* configured in obfuscation. field=" + resName);
        }

        try {
            Field field = resClass.getField(resName);
            return field.getInt(resName);
        } catch (Exception e) {

        }
        return -1;
    }
}